import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { API } from '../../utils/api'
import { BASE_URL } from '../../utils/url' 
import NavHeader from "../../components/Headnavbar"
import HouseItem from '../../components/HouseItem'
import NoHouse from '../../components/NoHouse'
import withHook from '../../utils/Withhook'
import styles from './index.module.css'
 
class Rent extends Component {
  state = {
    // 出租房屋列表
    list: []
  }
  // 获取当前用户已发布房源的列表数据，存入state：list
  async getHouseList() {
    const res = await API.get('/user/houses')

    const { status, body } = res.data
    //请求过期，则直接重新登录
    if (status === 200) {
      this.setState({
        list: body
      })
    } else {
      this.props.to('/login', {
        from: this.props.LC
      })
    }
  }

  componentDidMount() {
    this.getHouseList()
  }

  //渲染函数2：渲染已经发布的房源
  renderHouseItem() {
    const { list } = this.state
    return list.map(item => {
      return (
        <HouseItem
          key={item.houseCode}
          onClick={() => this.props.to(`/detail/${item.houseCode}`)}
          src={BASE_URL + item.houseImg}
          title={item.title}
          desc={item.desc}
          tags={item.tags}
          price={item.price}
        />
      )
    })
  }

  //渲染函数1，根据state：list判断如何来渲染当前已发布的资源，
  renderRentList() {
    const { list } = this.state
    const hasHouses = list.length > 0
    if (!hasHouses) {
      return (
        <NoHouse>
          您还没有房源，
          <Link to="/rent/add" className={styles.link}>
            去发布房源
          </Link>
          吧~
        </NoHouse>
      )
    }

    return <div className={styles.houses}>{this.renderHouseItem()}</div>
  }
  render() {

    return (
      <div className={styles.root}>
        <NavHeader onLeftClick={() => this.props.to(-1)}>房屋管理</NavHeader>

        {this.renderRentList()}
      </div>
    )
  }
}
const renthook = withHook(Rent)
export default renthook